package handler

import (
	"context"
	"crypto/sha512"
	"github.com/golang/protobuf/ptypes/empty"
	_ "github.com/golang/protobuf/ptypes/empty"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"gorm.io/gorm"
	"mxshop_srvs/user_srv/global"
	"mxshop_srvs/user_srv/model"
	"mxshop_srvs/user_srv/proto"
	"strings"
	"time"
)

type UserService struct {

}
func (s *UserService)GetUserList(ctx context.Context,req *proto.PageInfo) (*proto.UserListResponse, error){
	//获取用户列表
	var users []model.User
	result := global.DB.Find(&users)
	if result.Error != nil{
		return nil, result.Error
	}
	rsp := &proto.UserListResponse{}
	rsp.Total = int32(result.RowsAffected)

	global.DB.Scopes(Paginate(int(req.Pn),int(req.PSize)))

	for _, user := range users {
		userInfoRsp := ModelToResponse(user)
		rsp.Data = append(rsp.Data,&userInfoRsp)
	}

	return rsp,nil
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page == 0{
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
	
}
func (s *UserService)GetUserByMobile(ctx context.Context,req *proto.MobileRequest) (*proto.UserInfoResponse, error){
	var user model.User
	result := global.DB.Where(&model.User{Mobile: req.Mobile}).First(&user)
	if result.RowsAffected == 0 {
		return nil,status.Errorf(codes.NotFound,"用户不存在")
	}

	if result.Error != nil{
		return nil,result.Error
	}

	userInfoRsp := ModelToResponse(user)
	return &userInfoRsp,nil
}
func (s *UserService)GetUserById(ctx context.Context,req *proto.IdRequest) (*proto.UserInfoResponse, error){
	var user model.User
	result := global.DB.First(&user, req.Id)
	if result.RowsAffected == 0 {
		return nil,status.Errorf(codes.NotFound,"用户不存在")
	}

	if result.Error != nil{
		return nil,result.Error
	}

	userInfoRsp := ModelToResponse(user)
	return &userInfoRsp,nil
}
func (s *UserService)CreateUser(ctx context.Context,req *proto.CreateUserInfo) (*proto.UserInfoResponse, error){
	var user model.User
	result := global.DB.Where(&model.User{Mobile: req.Mobile}).First(&user)
	if result.RowsAffected == 1 {
		return nil, status.Errorf(codes.AlreadyExists, "用户已经存在")
	}

	user.Mobile = req.Mobile
	user.NickName = req.NickName

	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}

	userInfoRsp := ModelToResponse(user)
	return &userInfoRsp, nil
}
func (s *UserService)UpdateUser(ctx context.Context,req *proto.UpdateUserInfo) (*emptypb.Empty, error){
	var user model.User
	result := global.DB.First(&user, req.Id)
	if result.RowsAffected == 0{
		return nil, status.Errorf(codes.NotFound, "用户不存在")
	}

	birthDay := time.Unix(int64(req.BirthDay), 0)
	user.NickName = req.NickName
	user.Birthday = &birthDay
	user.Gender = req.Gender

	result = global.DB.Save(user)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}

	return &empty.Empty{},nil
}
func (s *UserService)CheckPassWord(ctx context.Context,req *proto.PasswordCheck) (*proto.CheckResponse, error){
	pwdSeq := strings.Split(req.EncryptedPassword, "$")
	options := &Options{16, 100, 32, sha512.New}
	check := Verify(req.Password, pwdSeq[2], pwdSeq[3], options)
	return &proto.CheckResponse{Success: check}, nil
}

//用于user转化UserInfoResponse
func ModelToResponse(user model.User) proto.UserInfoResponse {
	userInfoRsp := proto.UserInfoResponse{
		Id:       user.ID,
		PassWord: user.Password,
		NickName: user.NickName,
		Gender:   user.Gender,
		Role:     int32(user.Role),
	}

	if user.Birthday != nil {
		userInfoRsp.BirthDay = uint64(user.Birthday.Unix())
	}

	return userInfoRsp
}